package com.znjc.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.constant.DeviceConstants;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.DeviceDevice;
import com.znjc.device.domain.DevicePoint;
import com.znjc.device.domain.DeviceRuleRef;
import com.znjc.device.domain.IotDataResRule;
import com.znjc.device.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【设备测点与规则】Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/device/pointRuleRef")
public class DeviceRuleRefController extends BaseController {
    @Autowired
    private IDeviceRuleRefService deviceRuleRefService;
    @Autowired
    private IDevicePointService devicePointService;
    @Autowired
    private IIotDataResRuleService iotDataResRuleService;
    @Autowired
    private DeviceDataService deviceDataService;


    /**
     * 查询设备下测点与解析管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceRuleRef deviceRuleRef) {
        startPage();
        LambdaQueryWrapper<DeviceRuleRef> wrapper = getWrapper(deviceRuleRef);
        List<DeviceRuleRef> list = deviceRuleRefService.list(wrapper);
        return getDataTable(packList(list));
    }

    /**
     * 导出设备下测点与解析管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:device:export')")
    @Log(title = "设备下测点与解析管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceRuleRef deviceRuleRef) {
        LambdaQueryWrapper<DeviceRuleRef> wrapper = getWrapper(deviceRuleRef);
        List<DeviceRuleRef> list = deviceRuleRefService.list(wrapper);
        ExcelUtil<DeviceRuleRef> util = new ExcelUtil<DeviceRuleRef>(DeviceRuleRef.class);
        util.exportExcel(response, packList(list), "设备下测点与解析管理数据");
    }

    /**
     * 获取设备下测点与解析管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:device:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(deviceRuleRefService.getById(id));
    }

    /**
     * 新增设备下测点与解析管理
     */
    @PreAuthorize("@ss.hasPermi('device:device:add')")
    @Log(title = "设备下测点与解析管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceRuleRef deviceRuleRef) {
        if (deviceRuleRefService.verify(deviceRuleRef)) {
            return AjaxResult.error("已存在该测点与规则");
        }
        boolean flag = deviceRuleRefService.save(deviceRuleRef);
        /*if (flag) {
            DevicePoint point = devicePointService.getById(deviceRuleRef.getPointId());
            if (null != point) {
                deviceDataService.addColumn(DeviceConstants.TABLE_NAME+deviceRuleRef.getDeviceId(), point.getPointCode());
                deviceDataService.addColumn(DeviceConstants.TABLE_NAME+deviceRuleRef.getDeviceId(), point.getPointCode()+DeviceConstants.COLUMN_NAME);
            }
        }*/
        return toAjax(flag);
    }

    /**
     * 修改设备下测点与解析管理
     */
    @PreAuthorize("@ss.hasPermi('device:device:edit')")
    @Log(title = "设备下测点与解析管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceRuleRef deviceRuleRef) {
        if (deviceRuleRefService.verify(deviceRuleRef)) {
            return AjaxResult.error("已存在该测点与规则");
        }
        return toAjax(deviceRuleRefService.updateById(deviceRuleRef));
    }

    /**
     * 删除设备下测点与解析管理
     */
    @PreAuthorize("@ss.hasPermi('device:device:remove')")
    @Log(title = "设备下测点与解析管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<DeviceRuleRef> refs = deviceRuleRefService.listByIds(new ArrayList<>(Arrays.asList(ids)));
        boolean flag = deviceRuleRefService.removeByIds(new ArrayList<>(Arrays.asList(ids)));
        /*if (flag && CollectionUtils.isNotEmpty(refs)) {
            refs.forEach(deviceRuleRef -> {
                DevicePoint point = devicePointService.getById(deviceRuleRef.getPointId());
                if (null != point) {
                    deviceDataService.dropColumn(DeviceConstants.TABLE_NAME+deviceRuleRef.getDeviceId(), point.getPointCode());
                    deviceDataService.dropColumn(DeviceConstants.TABLE_NAME+deviceRuleRef.getDeviceId(), point.getPointCode()+DeviceConstants.COLUMN_NAME);
                }
            });

        }*/
        return toAjax(flag);
    }


    /**
     * 查询公共方法
     *
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(DeviceRuleRef entity) {
        LambdaQueryWrapper<DeviceRuleRef> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (null != entity.getDeviceId()) {
                wrapper.eq(DeviceRuleRef::getDeviceId, entity.getDeviceId());
            }
        }
        wrapper.orderByAsc(DeviceRuleRef::getSort);
        return wrapper;
    }

    /**
     * 结果封装
     *
     * @param list
     * @return
     */
    private List<DeviceRuleRef> packList(List<DeviceRuleRef> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if (null != entity.getPointId()) {
                    DevicePoint point = devicePointService.getById(entity.getPointId());
                    if (null != point) {
                        entity.setPointName(point.getPointName());
                    }
                }
                if (null != entity.getResRuleId()) {
                    IotDataResRule resRule = iotDataResRuleService.getById(entity.getResRuleId());
                    if (null != resRule) {
                        entity.setResRuleName(resRule.getRuleName());
                    }
                }
            });
        }
        return list;
    }
}
